package com.yejiarong.influxdb.api.config;

import com.yejiarong.common.enums.RequestHeaderKeyEnums;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.net.InetAddress;

/**
 * @author YeJR
 */
@Slf4j
public class HeaderInterceptor implements RequestInterceptor {

    @Value("${server.port}")
    private Integer serverPort;

    @Value("${spring.application.name}")
    private String serviceName;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 添加服务名或者IP端口, 用于服务端限流
        // 获取当前 JVM 实例的 IP 地址
        try {
            String ipAddress = InetAddress.getLocalHost().getHostAddress();
            requestTemplate.header(RequestHeaderKeyEnums.SERVER_PORT.name(), String.valueOf(serverPort));
            requestTemplate.header(RequestHeaderKeyEnums.SERVICE_NAME.name(), serviceName);
            requestTemplate.header(RequestHeaderKeyEnums.SERVICE_HOST.name(), String.valueOf(ipAddress));
        } catch (Exception e) {
            log.error("Append request header failed: {}", e.getMessage(), e);
        }
    }
}
